from server import db, api_auth, user_opt
from flask import jsonify, Blueprint, request, g
from server.model.gym import Gym
from server.model import set_field, query_by_field
import math

a_gym = Blueprint('app/gym', __name__)


@a_gym.route('', methods=['GET'])
def get_gyms():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in gym_list],
                            }
                """
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=20)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    query_filter = request.args.get('filter')

    try:

        gym_list = Gym.query

        if query_filter:
            gym_list = query_by_field(gym_list, query_filter, Gym)

        if start_time:
            gym_list = gym_list.filter(db.cast(Gym.create_time, db.Date) >= start_time)

        if end_time:
            gym_list = gym_list.filter(db.cast(Gym.create_time, db.Date) <= end_time)
        total = gym_list.count()

        gym_list = gym_list.offset((page - 1) * limit).limit(limit).all()

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': [u.to_dict() for u in gym_list],
            'totalCount': total,
            'TotalPageCount': math.ceil(int(total / limit))
        })
    except Exception as e:
        print("get gyms error:", e)

    return jsonify({'code': 50001, 'message': "查询球馆时发生错误"})


@a_gym.route('/<int:pid>', methods=['GET'])
def get_detail(pid):
    """
                    @@@
                    #### Args:
                           gym/id
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in gym_list],
                            }
                """
    gym = Gym.query.filter_by(id=pid).first()
    if not gym:
        return jsonify({
            'code': 50002,
            'message': '查询球馆不存在'
        })

    return jsonify({
        'code': 20000,
        'message': 'success',
        'items': gym.to_dict(),
    })

# >>>>> auto generate end <<<<<
